package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@Service
public class CommentApiImpl implements CommentApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public PageResult findAll(Integer page, Integer pageSize, String publishId) {
        //1、构造查询条件
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(publishId)).and("commentType").is(2);
        Query query = new Query(criteria)
                .limit(pageSize).skip((page-1) * pageSize)
                .with(Sort.by(Sort.Order.desc("created")));
        //2、查询数据列表
        List<Comment> list = mongoTemplate.find(query, Comment.class);
        //3、查询总记录数
        long count = mongoTemplate.count(query, Comment.class);
        //4、构造返回值
        return new PageResult(page,pageSize,(int) count,list);
    }

    /**
     * 保存
     *  comment对象中包含一个publishId字段（操作的动态id）
     */
    public long save(Comment comment) {
        //1、设置id和发布时间
        comment.setId(ObjectId.get());
        comment.setCreated(System.currentTimeMillis());
        //根据id查询动态
        if(comment.getPubType() == 1) {
            Publish publish = mongoTemplate.findById(comment.getPublishId(), Publish.class);
            comment.setPublishUserId(publish.getUserId());
        }else if(comment.getPubType() == 2) {
            Video video = mongoTemplate.findById(comment.getPublishId(), Video.class);
            comment.setPublishUserId(video.getUserId());
        }
        //2、保存到mongodb中
        mongoTemplate.save(comment);
        //3、修改动态表中的点赞数量
        Query query = new Query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        //指定更新的字段
        update.inc(comment.getCol(),1);
        if(comment.getPubType() == 1) {
            mongoTemplate.updateFirst(query, update, Publish.class);
        }else if(comment.getPubType() == 2) {
            mongoTemplate.updateFirst(query, update, Video.class);
        }
        //4、查询点赞之后总的点赞数量,统计comment表中的统计总数量
        Query countQuery = new Query(
                Criteria.where("publishId").is(comment.getPublishId())
                .and("commentType").is(comment.getCommentType())
        );
        return mongoTemplate.count(countQuery,Comment.class);
    }

    /**
     * 删除
     */
    public long remove(Comment comment) {
        //1、删除指定的comment数据
        Query removeQuery = new Query(
                Criteria.where("publishId").is(comment.getPublishId())
                .and("userId").is(comment.getUserId())
                .and("commentType").is(comment.getCommentType())
        );
        mongoTemplate.remove(removeQuery,Comment.class);
        //2、修改动态表中的点赞数量
        Query query = new Query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        //指定更新的字段
        update.inc(comment.getCol(),-1);

        mongoTemplate.updateFirst(query,update, Publish.class);
        //3、查询点赞之后的总点赞数量
        Query countQuery = new Query(
                Criteria.where("publishId").is(comment.getPublishId())
                        .and("commentType").is(comment.getCommentType())
        );
        return mongoTemplate.count(countQuery,Comment.class);
    }

    /**
     * 问题
     *  userId：被评论人的id
     *  bug：需要在评论表中，添加一个新的字段
     *        被点赞，评论人的ID（动态，视频的发布作者）
     */
    public PageResult messageList(Integer page, Integer pagesize, int commentType, Long userId) {
        Query query = new Query(
                Criteria.where("commentType").is(commentType)
                .and("publishUserId").is(userId)
        ).limit(pagesize).skip((page - 1) * pagesize);
        List<Comment> list = mongoTemplate.find(query, Comment.class);
        long count = mongoTemplate.count(query, Comment.class);
        return new PageResult(page,pagesize,(int) count,list);
    }
}
